﻿using MediatR;
using RBAC.Api.Demain.ContentManagement;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Read.Command.ContentManagement;

namespace RBAC.Api.Read.CommandHandler.ContentManagement
{
    public class ShowCarouselChartCommandHandler : IRequestHandler<ShowCarouselChartCommand, APIResult<APIPagin<CarouselChartModel>>>
    {
        private readonly IBaseRepositry<CarouselChartModel> baseRepositry;

        public ShowCarouselChartCommandHandler(IBaseRepositry<CarouselChartModel> baseRepositry)
        {
            this.baseRepositry = baseRepositry;
        }
        public Task<APIResult<APIPagin<CarouselChartModel>>> Handle(ShowCarouselChartCommand request, CancellationToken cancellationToken)
        {
             APIResult<APIPagin<CarouselChartModel>> result=new APIResult<APIPagin<CarouselChartModel>>();
            result.Message = "获取轮播图表成功";
            result.Code= ResultCode.Success;

            var list = baseRepositry.GetAll();
             if(!string.IsNullOrEmpty(request.Title))
             {
                list = list.Where(x => x.Title.Contains(request.Title));
             }
            if ((request.StartTime != null && request.EndTime != null))
            {
                list=list.Where(x=>x.StartTime>=request.StartTime && x.EndTime<=request.EndTime);
            }
            var totalCount = list.Count();
            var page = (int)Math.Ceiling((totalCount * 1.0) / request.PageSize);
            list=list.OrderByDescending(x=>x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            APIPagin<CarouselChartModel> res = new APIPagin<CarouselChartModel>()
            {
                TotaleCount = totalCount,
                PageCount = page,
                List = list.ToList()
            };

            result.Data = res;

            return Task.FromResult(result);
        }
    }
}
